# coding:utf-8
class Admin::AccountGroupsController < AdminController
	
  respond_to :html, :json

  before_filter :setup, only: [:index]

  set_tab :business

  def index
    set_tab :account_groups, :sub_nav
    @account_groups = AccountGroup.order('id ASC').page(params[:page])
	end

  def new
    @account_group = AccountGroup.new
    @accounts = []
  end

  def edit
    @account_group = AccountGroup.find params[:id]
    @accounts = Account.where(account_group_id: @account_group.id)
  end

  def create
    account_ids = params[:account_group].delete(:account_ids)
    @account_group = AccountGroup.new(params[:account_group])
    if @account_group.save
      Account.where(id: account_ids).each do |t|
        t.account_group_id = @account_group.id
        t.save!
      end
    else
      render :action => :new 
    end
  end

  def update
    account_ids = params[:account_group].delete(:account_ids)
    @account_group = AccountGroup.find params[:id]
    if @account_group.update_attributes(params[:account_group])
      # set null for pre-group
      unless @account_group.default
        Account.where(account_group_id: @account_group.id).each do |t|
          t.account_group_id = nil
          t.save!
        end

        # set the new group
        Account.where(id: account_ids).each do |t|
          t.account_group_id = @account_group.id
          t.save!
        end
      end
    else
      render :action => :edit 
    end
  end

  def destroy
    @account_group = AccountGroup.find params[:id]
    @account_group.destroy
  end

  private

  def setup
    @ways = ["业务","用户分组管理"]
    @left_panel = "layouts/account_widget"
  end

end